/**
 *
 */
package com.iknight.mgr.controller;

import com.github.pagehelper.PageInfo;
import com.iknight.mgr.api.PermGroupService;
import com.iknight.mgr.api.PermissionService;
import com.iknight.mgr.core.base.BaseController;
import com.iknight.mgr.core.constant.IkgConstantCode;
import com.iknight.mgr.core.jstree.JsTreeNode;
import com.iknight.mgr.core.jstree.NodeStatus;
import com.iknight.mgr.core.utils.IkgStringUtils;
import com.iknight.mgr.core.utils.IkgWebUtils;
import com.iknight.mgr.model.PermGroupModel;
import com.iknight.mgr.model.PermissionModel;
import net.sf.json.JSONArray;
import net.sf.json.JSONObject;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.*;

/**
 * @author Jeryzym
 */
@RestController
@RequestMapping("/rest/perm")
public class PermissionController implements BaseController<PermissionModel> {

    private static Logger logger = LogManager.getLogger(PermissionController.class);

    @Autowired
    private PermissionService<PermissionModel, String> permissionService;
    @Autowired
    private PermGroupService<PermGroupModel, String> permGroupService;

    @Value("${enableRoot}")
    private boolean enableRoot;
    @Value("${rootName}")
    private String rootName;

    public PermissionModel format(Map<String, Object> params) {
        // TODO Auto-generated method stub
        PermissionModel record = new PermissionModel();
        record.setPerm_id(IkgStringUtils.ObjectToString(params.get("perm_id")));
        if (!IkgStringUtils.isNull(params.get("perm_code"))) {
            record.setPerm_code(IkgStringUtils.ObjectToString(params.get("perm_code")));
        }
        if (!IkgStringUtils.isNull(params.get("perm_name"))) {
            record.setPerm_name(IkgStringUtils.ObjectToString(params.get("perm_name")));
        }
        if (!IkgStringUtils.isNull(params.get("app_id"))) {
            record.setApp_id(IkgStringUtils.ObjectToString(params.get("app_id")));
        }
        if (!IkgStringUtils.isNull(params.get("edit_status"))
                && IkgStringUtils.ObjectToString(params.get("edit_status")).equals("0")) {
            record.setEffective_date(IkgStringUtils.getCurrentDate("yyyy-MM-dd HH:mm"));
        }
        if (!IkgStringUtils.isNull(params.get("record_status"))) {
            record.setRecord_status(IkgStringUtils.ObjectToInt(params.get("record_status")));
        }
        if (!IkgStringUtils.isNull(params.get("expire_date"))) {
            record.setExpire_date(IkgStringUtils.ObjectToString(params.get("expire_date")));
        }
        return record;
    }

    @PostMapping("/save")
//	@RequiresPermissions("mgr.perm.save")
//	@RequiresRoles("admin")
    public Object save(@RequestBody Map<String, Object> params, HttpServletRequest request,
                       HttpServletResponse response) {
        // TODO Auto-generated method stub
        if (!isPKeyNotNull(params)) {
            return IkgWebUtils.postIkgResponse(false, "传入参数为空", IkgConstantCode.PARAMSNULL);
        }
        permissionService.save(format(params));
        return IkgWebUtils.postIkgResponse(true, "保存成功", IkgConstantCode.OPERSUCCESS);
    }

    @PostMapping("/delete")
//	@RequiresPermissions("mgr.perm.delete")
//	@RequiresRoles("admin")
    public Object delete(@RequestBody Map<String, Object> params, HttpServletRequest request,
                         HttpServletResponse response) {
        // TODO Auto-generated method stub
        // return 0;
        if (!isPKeyNotNull(params)) {
            return IkgWebUtils.postIkgResponse(false, "传入参数为空", IkgConstantCode.PARAMSNULL);
        }
        permissionService.delete(IkgStringUtils.ObjectToString(params.get("perm_id")));
        return IkgWebUtils.postIkgResponse(true, "删除成功!", IkgConstantCode.OPERSUCCESS);
    }

    @PostMapping("/selectOne")
//	@RequiresPermissions("mgr.perm.selectone")
//	@RequiresRoles("admin")
    public Object selectOne(@RequestBody Map<String, Object> params, HttpServletRequest request,
                            HttpServletResponse response) {
        // TODO Auto-generated method stub
        if (!isPKeyNotNull(params)) {
            return IkgWebUtils.postIkgResponse(false, "传入参数为空", IkgConstantCode.PARAMSNULL);
        }
        return IkgWebUtils.postIkgResponse(true, "查询成功!", permissionService.selectOne(IkgStringUtils.ObjectToString(params.get("perm_id"))));
    }

    public Object selectByCond(@RequestBody Map<String, Object> params, HttpServletRequest request,
                               HttpServletResponse response) {
        // TODO Auto-generated method stub
        return null;
    }

    @PostMapping("/repeatCheck")
    public Object repeatCheck(@RequestBody Map<String, Object> params, HttpServletRequest request,
                              HttpServletResponse response) {
        if (params == null || params.get("perm_code") == null) {
            return IkgWebUtils.postIkgResponse(false, "传入参数为空", IkgConstantCode.PARAMSNULL);
        }
        String perm_code = params.get("perm_code").toString();
        PermissionModel record = permissionService.getRecordByCode(perm_code);
        if (record == null) {
            return IkgWebUtils.postIkgResponse(true, "通过编码重复检测", IkgConstantCode.OPERSUCCESS);
        }
        return IkgWebUtils.postIkgResponse(false, "未通过编码重复检测", IkgConstantCode.OPERSUCCESS);
    }

    public boolean isPKeyNotNull(Map<String, Object> params) {
        return params != null && params.get("perm_id") != null;
    }

    @Override
    @PostMapping("/list")
//	@RequiresPermissions("mgr.perm.list")
//	@RequiresRoles("admin")
    public Object selectByPage(@RequestBody Map<String, Object> params, HttpServletRequest request,
                               HttpServletResponse response) {
        // TODO Auto-generated method stub
        int pageIndex = 0;
        int pageSize = 0;
        if (params == null) {
            return IkgWebUtils.postIkgResponse(false, "传入参数为空", IkgConstantCode.PARAMSNULL);
        }
        pageIndex = IkgStringUtils.ObjectToInt(params.get("pageNumber"));
        pageSize = IkgStringUtils.ObjectToInt(params.get("pageSize"));

        PageInfo<PermissionModel> perms = permissionService.selectPage(params, pageIndex, pageSize);
        return IkgWebUtils.postResult(perms.getTotal(), perms.getList());
    }

    @PostMapping("/group/loadGroupTree")
    public Object loadTreeNodes(HttpServletRequest request, HttpServletResponse response) {

        List<PermGroupModel> result = permGroupService.selectAll();
        List<JsTreeNode> nodes = new ArrayList<>();
        JsTreeNode rootNode = new JsTreeNode();
        String rootId = null;
        if (enableRoot) {
            rootId = UUID.randomUUID().toString();
            rootNode.setId(rootId);
            rootNode.setText(rootName);
            rootNode.setParent("#");
            rootNode.setState(new NodeStatus(false, false, false, false));
            JSONObject rootAttr = new JSONObject();
            rootAttr.put("isRoot", true);
            rootNode.setAttributes(rootAttr);
            nodes.add(rootNode);
        }

        Iterator ita = result.iterator();
        while (ita.hasNext()) {
            PermGroupModel record = (PermGroupModel) ita.next();
            JsTreeNode node = new JsTreeNode();
            node.setId(record.getPerm_group_id());
            node.setText(record.getPerm_group_name());
            node.setIcon("fa fa-balance-scale");
            if (IkgStringUtils.ObjectToString(record.getP_perm_group_id()).trim().length() == 0) {
                if (enableRoot) {
                    node.setParent(rootNode.getId());
                } else {
                    node.setParent("#");
                }
            } else {
                node.setParent(record.getP_perm_group_id());
            }
            JSONObject attr = new JSONObject();
            attr.put("code", record.getPerm_group_code());
            node.setAttributes(attr);
            node.setState(new NodeStatus(false, false, false, false));
            nodes.add(node);
        }
        return JSONArray.fromObject(nodes);
    }

    private PermGroupModel formatPermGroupModel(Map<String, Object> params) {
        PermGroupModel record = new PermGroupModel();
        record.setPerm_group_id(IkgStringUtils.ObjectToString(params.get("perm_group_id")));
        record.setPerm_group_code(IkgStringUtils.ObjectToString(params.get("perm_group_code")));
        record.setPerm_group_name(IkgStringUtils.ObjectToString(params.get("perm_group_name")));

        if (!IkgStringUtils.ObjectToString(params.get("p_p_perm_group_id")).equals("#")) {
            record.setP_perm_group_id(IkgStringUtils.ObjectToString(params.get("p_perm_group_id")));
        }
        return record;
    }

    @PostMapping("/group/save")
    public Object savePermGroup(@RequestBody Map<String, Object> params, HttpServletRequest request,
                                HttpServletResponse response) {
        PermGroupModel record = formatPermGroupModel(params);
        permGroupService.save(record);
        return IkgWebUtils.postIkgResponse(true, "保存成功!", IkgConstantCode.OPERSUCCESS);
    }

    @PostMapping("/group/delete")
    public Object deletePermGroup(@RequestBody Map<String, Object> params, HttpServletRequest request,
                                  HttpServletResponse response) {
        String pKey = IkgStringUtils.ObjectToString(params.get("perm_group_id"));
        permGroupService.delete(pKey);
        return IkgWebUtils.postIkgResponse(true, "删除成功!", IkgConstantCode.OPERSUCCESS);
    }

    @PostMapping("/group/update")
    public Object updatePermGroup(@RequestBody Map<String, Object> params, HttpServletRequest request,
                                  HttpServletResponse response) {
        PermGroupModel record = formatPermGroupModel(params);
        permGroupService.save(record);
        return IkgWebUtils.postIkgResponse(true, "更新成功!", IkgConstantCode.OPERSUCCESS);
    }

}
